package cn.stu.flowable.controller;


import cn.stu.common.utils.R;
import cn.stu.flowable.domain.dto.FlowSaveXmlVo;
import cn.stu.flowable.service.IFlowDefinitionService;
import cn.stu.framework.entity.Role;
import cn.stu.framework.entity.SysExpression;
import cn.stu.framework.entity.UsersDetail;
import cn.stu.framework.service.ISysExpressionService;
import cn.stu.framework.service.RoleService;
import cn.stu.framework.service.UsersDetailService;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 流定义控制器
 * 工作流程定义
 *
 * @author Tony
 * @date 2021-04-03
 * @menu 工作流程定义
 */
@Slf4j
@RestController
@RequestMapping("/flowable/definition")
public class FlowDefinitionController {

    /**
     * 流定义服务
     */
    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    /**
     * 用户详细信息服务
     */
    @Autowired
    private UsersDetailService usersDetailService;

    /**
     * 系统角色服务
     */
    @Resource
    private RoleService sysRoleService;
    /**
     * Sys Expression服务
     */
    @Resource
    private ISysExpressionService sysExpressionService;

    /**
     * 流程定义列表
     *
     * @param pageNum  一页上一页
     * @param pageSize 页面大小
     * @param name     名字
     * @return {@link R}
     */
    @GetMapping(value = "/list")
    public R list(@ApiParam(value = "当前页码", required = true) @RequestParam Integer pageNum,
                  @ApiParam(value = "每页条数", required = true) @RequestParam Integer pageSize,
                  @ApiParam(value = "流程名称", required = false) @RequestParam(required = false) String name) {
        return R.ok(flowDefinitionService.list(name, pageNum, pageSize));
    }


    /**
     * 导入流程文件
     *
     * @param name     名字
     * @param category 范畴
     * @param file     文件
     * @return {@link R}
     */
    @PostMapping("/import")
    public R importFile(@RequestParam(required = false) String name,
                        @RequestParam(required = false) String category,
                        MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            flowDefinitionService.importFile(name, category, in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return R.ok(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }
        return R.ok("导入成功");
    }


    /**
     * 读取xml文件
     *
     * @param deployId 部署ID
     * @return {@link R}
     */
    @GetMapping("/readXml/{deployId}")
    public R readXml(@ApiParam(value = "流程定义id") @PathVariable(value = "deployId") String deployId) {
        try {
            return flowDefinitionService.readXml(deployId);
        } catch (Exception e) {
            return R.failed("加载xml文件异常");
        }
    }

    /**
     * 读取图片文件
     *
     * @param deployId 部署ID
     * @param response 响应
     */
    @GetMapping("/readImage/{deployId}")
    public void readImage(@ApiParam(value = "流程定义id") @PathVariable(value = "deployId") String deployId, HttpServletResponse response) {
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(flowDefinitionService.readImage(deployId));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 保存流程设计器内的xml文件
     *
     * @param vo Vo
     * @return {@link R}
     */
    @PostMapping("/save")
    public R save(@RequestBody FlowSaveXmlVo vo) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(vo.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(vo.getName(), vo.getCategory(), in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return R.failed(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }
        return R.ok("导入成功");
    }


    /**
     * 发起流程
     *
     * @param procDefId 进程定义ID
     * @param variables 变数
     * @return {@link R}
     */
    @PostMapping("/start/{procDefId}")
    public R start(@ApiParam(value = "流程定义id") @PathVariable(value = "procDefId") String procDefId,
                   @ApiParam(value = "变量集合,json对象") @RequestBody Map<String, Object> variables) {
        return flowDefinitionService.startProcessInstanceById(procDefId, variables);
    }

    /**
     * 激活或挂起流程定义
     *
     * @param state    状态
     * @param deployId 部署ID
     * @return {@link R}
     */
    @PutMapping(value = "/updateState")
    public R updateState(@ApiParam(value = "1:激活,2:挂起", required = true) @RequestParam Integer state,
                         @ApiParam(value = "流程部署ID", required = true) @RequestParam String deployId) {
        flowDefinitionService.updateState(state, deployId);
        return R.ok();
    }

    /**
     * 删除流程
     *
     * @param deployIds 部署ID
     * @return {@link R}
     */
    @DeleteMapping(value = "/{deployIds}")
    public R delete(@PathVariable String[] deployIds) {
        for (String deployId : deployIds) {
            flowDefinitionService.delete(deployId);
        }
        return R.ok();
    }

    /**
     * 指定流程办理人员列表
     *
     * @param usersDetail 用户详细信息
     * @return {@link R}
     */
    @GetMapping("/userList")
    public R userList(UsersDetail usersDetail) {
        return usersDetailService.selectUserList(usersDetail);
    }

    /**
     * 指定流程办理组列表
     *
     * @param role 角色
     * @return {@link R}<{@link List}<{@link Role}>>
     */
    @GetMapping("/roleList")
    public R<List<Role>> roleList(Role role) {
        return sysRoleService.selectRoleList(role);
    }

    /**
     * 指定流程达式列表
     *
     * @param sysExpression Sys表达式
     * @return {@link R}
     */
    @GetMapping("/expList")
    public R expList(SysExpression sysExpression) {
        return sysExpressionService.selectSysExpressionList(sysExpression);
    }
}
